//
//  JsWebImage.m
//  JsoUtilitySdk
//
//  Created by Gikki Ares on 2021/8/12.
//

#import "JsWebImageManager.h"
#import "JsWebImageMemoryCache.h"
#import "JsBundleManager.h"

@interface JsWebImageManager ()

@property(nonatomic,strong)UIImage * placeholder;

@end

@implementation JsWebImageManager

static JsWebImageManager * _sharedInstance;
+ (JsWebImageManager * )sharedInstance {
	static dispatch_once_t onceToken;
	dispatch_once(&onceToken,^{
		_sharedInstance = [JsWebImageManager new];
	});
	return _sharedInstance;
}

- (instancetype)init {
	if(self = [super init]) {
		self.placeholder = [JsBundleManager iconInBundleNamed:@"ImageLoading" inDir:@"Placeholder"];
	}
	return self;
}


+ (void)downloadImageWithUrlString:(NSString *)urlString completionHandler:(void(^)(UIImage * image))handler {
//	[[JsRequestManager sharedInstance] getDownloadWithInterfaceUrlString:urlString requestParameter:nil completionHandler:^(int responseState, NSData * resultData, NSString * _Nonnull requestDetail) {
//		//下载成功则调用回调.如果获取到图片则返回图片并缓存,否则返回nil;
//		if(responseState == 200 && resultData.length) {
//			UIImage * image = [UIImage imageWithData:resultData];
//			[[JsWebImageMemoryCache sharedInstance] cacheImage:image forKey:urlString];
//			handler(image);
//		}
//		else {
//			handler(nil);
//		}
//	}];
}

@end


@implementation UIImageView (JsWebImage)

//使用默认占位图?
-(void)setImageWithUrlString:(NSString *)urlString {
	[self setImageWithUrlString:urlString placeholder:nil];
}

-(void)setImageWithUrlStringAndDefaultPlaceholder:(NSString *)urlString {
	UIImage * placeholder = [JsWebImageManager sharedInstance].placeholder;
	[self setImageWithUrlString:urlString placeholder:placeholder];
}

-(void)setImageWithUrlString:(NSString *)urlString placeholder:(nullable UIImage *)placeholder {
	UIImage * image = [[JsWebImageMemoryCache sharedInstance] imageForKey:urlString];
	if(!image) {
		if(placeholder) {
			self.image = placeholder;
		}
		[JsWebImageManager downloadImageWithUrlString:urlString completionHandler:^(UIImage * _Nonnull image) {
			if(image) {
				self.image = image;
			}
		}];
	}
	else {
		self.image = image;
	}
}

@end
